import {getStore, setStore} from '@/util/store'
import {isURL} from '@/util/validate'
import {loginByUsername, logout} from '@/modules/sys/api/login'
import {getUserInfo} from '@/modules/sys/api/user'
import {deepClone, encryption} from '@/util/util'
import webiste from '@/const/website'
import {GetMenu} from '@/modules/sys/api/menu'

function addPath(ele, first) {
  const propsConfig = webiste.menu.props
  const propsDefault = {
    label: propsConfig.label || 'label',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children'
  }
  const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0
  if (!isChild && first) {
    ele[propsDefault.path] = ele[propsDefault.path] + '/index'
    return
  }
  if (ele[propsDefault.children]){
    ele[propsDefault.children].forEach(child => {
      if (!isURL(child[propsDefault.path])
        &&!(child[propsDefault.path] && child[propsDefault.path].includes('?'))) {
        child[propsDefault.path] = `${ele[propsDefault.path]}/${child[propsDefault.path] ? child[propsDefault.path] : 'index'}`
      }
      addPath(child)
    })
  }
}

const user = {
  state: {
    userInfo: {},
    permissions: {},
    // roles: [],
    menu: [],
    // menuAll: [],
    // expires_in: getStore({
    //   name: 'expires_in'
    // }) || '',
    access_token: getStore({
      name: 'access_token'
    }) || '',
    auth_token: getStore({
        name: 'auth_token'
      }) || ''
    // refresh_token: getStore({
    //   name: 'refresh_token'
    // }) || ''
  },
  actions: {
    // 根据用户名登录
    LoginByUsername({commit}, userInfo) {
      const user = encryption({
        data: userInfo,
        key: 'chcitchcitchcitx',
        param: ['password']
      })
      return new Promise((resolve, reject) => {
        loginByUsername(user.username, user.password, user.code, user.randomStr).then(response => {
          const data = response.data
          if(data && data.code==0){
            //commit('SET_LOGIN', true)
            commit('SET_ACCESS_TOKEN', data.data.chcitToken)
            commit('SET_AUTH_TOKEN', data.data.token) //单点登录token
            // commit('SET_REFRESH_TOKEN', data.refresh_token)
            // commit('SET_EXPIRES_IN', data.expires_in)
            // commit('CLEAR_LOCK')
            resolve()
          }
          else {
            reject(data.msg)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // // 根据手机号登录
    // LoginByPhone({commit}, userInfo) {
    //   return new Promise((resolve, reject) => {
    //     loginByMobile(userInfo.mobile, userInfo.code).then(response => {
    //       const data = response.data
    //       commit('SET_ACCESS_TOKEN', data.access_token)
    //       commit('SET_REFRESH_TOKEN', data.refresh_token)
    //       commit('SET_EXPIRES_IN', data.expires_in)
    //       commit('CLEAR_LOCK')
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // // 根据OpenId登录
    // LoginBySocial({commit}, param) {
    //   return new Promise((resolve, reject) => {
    //     loginBySocial(param.state, param.code).then(response => {
    //       const data = response.data
    //       commit('SET_ACCESS_TOKEN', data.access_token)
    //       commit('SET_REFRESH_TOKEN', data.refresh_token)
    //       commit('SET_EXPIRES_IN', data.expires_in)
    //       commit('CLEAR_LOCK')
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    GetUserInfo({commit}) {
      return new Promise((resolve, reject) => {
        getUserInfo().then((res) => {
          const data = res.data.data || {}
          commit('SET_USER_INFO', data)
          //commit('SET_ROLES', data.roles || [])
          commit('SET_PERMISSIONS', data.permissions || [])
          resolve(data)
        }).catch((err) => {
          reject()
        })
      })
    },
    // // 刷新token
    // RefreshToken({commit, state}) {
    //   return new Promise((resolve, reject) => {
    //     refreshToken(state.refresh_token).then(response => {
    //       const data = response.data
    //       commit('SET_ACCESS_TOKEN', data.access_token)
    //       commit('SET_REFRESH_TOKEN', data.refresh_token)
    //       commit('SET_EXPIRES_IN', data.expires_in)
    //       commit('CLEAR_LOCK')
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // 登出
    LogOut({commit}) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_MENU', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_USER_INFO', {})
          commit('SET_ACCESS_TOKEN', '')
          commit('SET_AUTH_TOKEN', '')
          // commit('SET_REFRESH_TOKEN', '')
          // commit('SET_EXPIRES_IN', '')
          // commit('SET_ROLES', [])
          commit('DEL_ALL_TAG')
          commit('CLEAR_LOCK')
          //commit('SET_LOGIN',false)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 注销session
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_MENU', [])
        commit('SET_PERMISSIONS', [])
        commit('SET_USER_INFO', {})
        commit('SET_ACCESS_TOKEN', '')
        commit('SET_AUTH_TOKEN', '')
        // commit('SET_REFRESH_TOKEN', '')
        // commit('SET_ROLES', [])
        commit('DEL_ALL_TAG')
        commit('CLEAR_LOCK')
        resolve()
      })
    },
    // 获取系统菜单
    GetMenu({
              commit
            }) {
      return new Promise(resolve => {
        GetMenu().then((res) => {
					if (res && res.data && res.data.data){
						const data = res.data.data.children
            let hospitalMenue=  {
              'id': 'regis',
              'label': '排班管理',
              'path': '/regis',
              'component': 'Layout',
              'icon': 'icon-msnui-supervise',
              'children': [{
                'id': 'regis.template',
                'label': '科室排班',
                'path': 'ware/schedule',
                'component': 'modules/regis/views/ware-schedule/index',
                'leaf': false,
                'keepAlive': false,
              },
                {
                  'id': 'regis.workforce.management',
                  'label': '班次设置',
                  'path': 'workforce',
                  'component': 'modules/regis/views/workforce-management/index',
                  'leaf': true,
                  'keepAlive': true,
                },
                {
                  'id': 'regis.person.schedule',
                  'label': '个人排班查询',
                  'path': 'person/schedule',
                  'component': 'modules/regis/views/person-schedule/index',
                  'leaf': true,
                  'keepAlive': true,
                },
                {
                  'id': 'regis.setting.template',
                  'label': '模板设置',
                  'path': 'setting/template',
                  'component': 'modules/regis/views/setting-template/index',
                  'leaf': true,
                  'keepAlive': true,
                },
                {
                  'id': 'regis.guahao',
                  'label': '挂号管理',
                  'path': 'setting/guahao',
                  'component': 'modules/regis/views/guahao/index',
                  'leaf': true,
                  'keepAlive': true,
                }
              ]
            }
            data.push(hospitalMenue)
						let menu = deepClone(data)
						menu.forEach(ele => {
							addPath(ele)
						})
						commit('SET_MENU', menu)
						resolve(menu)
					}
        })
      })
    }

  },
  mutations: {
    SET_ACCESS_TOKEN: (state, access_token) => {
      state.access_token = access_token
      setStore({
        name: 'access_token',
        content: state.access_token,
        type: 'session'
      })
      //供ureport使用
      window.chcToken = access_token;
    },
    SET_AUTH_TOKEN: (state, auth_token) => {
        state.auth_token = auth_token
        setStore({
          name: 'auth_token',
          content: state.auth_token,
          type: 'session'
        })
        //供ureport使用
        window.token = auth_token;
      },
    // SET_EXPIRES_IN: (state, expires_in) => {
    //   state.expires_in = expires_in
    //   setStore({
    //     name: 'expires_in',
    //     content: state.expires_in,
    //     type: 'session'
    //   })
    // },
    // SET_REFRESH_TOKEN: (state, rfToken) => {
    //   state.refresh_token = rfToken
    //   setStore({
    //     name: 'refresh_token',
    //     content: state.refresh_token,
    //     type: 'session'
    //   })
    // },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      setStore({
        name: 'menu',
        content: state.menu,
        type: 'session'
      })
    },
    // SET_MENU_ALL: (state, menuAll) => {
    //   state.menuAll = menuAll
    // }
    // SET_ROLES: (state, roles) => {
    //   state.roles = roles
    // },
    SET_PERMISSIONS: (state, permissions) => {
      const list = {}
      for (let i = 0; i < permissions.length; i++) {
        list[permissions[i]] = true
      }
      state.permissions = list
    }
  }

}
//供ureport使用
window.chcToken = user.state.access_token;
window.token = user.state.auth_token;
export default user
